package cn.com.zte.ngbc.dao.mybatis.dynamicsql.node;

import org.dom4j.Element;

import cn.com.zte.common.util.StringUtil;
import cn.com.zte.ngbc.dao.mybatis.dynamicsql.DynamicContext;
import cn.com.zte.ngbc.frw.model.sql.dynamic.AndSqlNode;
import cn.com.zte.ngbc.frw.model.sql.dynamic.IfSqlNode;
import cn.com.zte.ngbc.frw.model.sql.dynamic.OrSqlNode;
import cn.com.zte.ngbc.frw.model.sql.dynamic.SqlNode;
import cn.com.zte.ngbc.frw.model.sql.dynamic.StrSqlNode;
import cn.com.zte.ngbc.frw.model.sql.dynamic.WhereSqlNode;

public class WhereSqlNodeHandler
  implements SqlNodeHandler
{
  private WhereSqlNode where;
  
  public WhereSqlNodeHandler(WhereSqlNode where)
  {
    this.where = where;
  }
  
  public String process(DynamicContext context)
  {
    if (this.where == null) {
      throw new IllegalArgumentException("未配置where条件");
    }
    StringBuilder sqlBuilder = new StringBuilder();
    sqlBuilder.append("where ");
    
    Element selectEle=  context.selectEle;
    Element whereEle=  selectEle.addElement("where");
    whereEle.addCDATA(" 1=1 ");
    context.selectEle=whereEle;
    SqlNode logic = this.where.getLogic();
    String childSql;
    try
    {
      SqlNodeHandler sqlNodeHandler;
      if ((logic instanceof StrSqlNode))
      {
        sqlNodeHandler = new StrSqlNodeHandler((StrSqlNode)logic);
      }
      else
      {

        if ((logic instanceof IfSqlNode))
        {
          sqlNodeHandler = new IfSqlNodeHandler((IfSqlNode)logic);
        }
        else
        {

          if ((logic instanceof AndSqlNode))
          {
            sqlNodeHandler = new AndSqlNodeHandler((AndSqlNode)logic);
          }
          else
          {

            if ((logic instanceof OrSqlNode))
            {
              sqlNodeHandler = new OrSqlNodeHandler((OrSqlNode)logic);
            }
            else
            {
              if (logic == null) {
                throw new IllegalArgumentException("where条件未配置逻辑运算符");
              }
              throw new IllegalArgumentException("不支持该逻辑运算符[" + logic.getClass().getSimpleName() + "]");
            }
          }
        }
      }
      childSql = sqlNodeHandler.process(context);
    }
    catch (Exception e)
    {
      throw new IllegalArgumentException("解析sql的where条件出错 , cause by :" + e.getMessage(), e);
    }
    if (StringUtil.isEmpty(childSql)) {
      return null;
    }
    
    context.selectEle=selectEle;
    return childSql.trim();
  }
}